
/**
 *
 *  Copyright 2019 The FATE Authors. All Rights Reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

import { each } from '../fn/uitls'
import { createFormComponent, createOption } from '../fn/common.js'

const getHeader = () => {
  return [
    {
      prop: 'label',
      label: 'label',
      sortable: true
    },
    {
      prop: 'original_count',
      label: 'original_count',
      sortable: true
    },
    {
      prop: 'sample_count',
      label: 'sample_count',
      sortable: true
    }
  ]
}

const getFormSetting = (tableData) => {
  const formSetting = []
  formSetting.push(createFormComponent(
    'f-select',
    'f-selection',
    {
      options: ((Object.keys(tableData)).map((item) => {
        return createOption(item)
      })).reverse(),
      multiple: false
    }
  ))
  return formSetting
}

const appendArray = (target, arr) => {
  each(target, (item, i) => {
    item.push(arr[i][1])
  })
  return target
}

const fn = (response) => {
  const key = []
  const tableData = {}
  let rowData = []
  let all = []
  each(response, (row, j) => {
    key.push(row.stratified.meta.name)
    rowData.length === 0 ? rowData = row.stratified.data : appendArray(rowData, row.stratified.data)
  })
  each(rowData, (data, i) => {
    const item = {}
    item.label = i
    each(key, (name, j) => {
      item[name] = data[j + 1]
    })
    tableData[i] = item
    all = all.concat(item)
  })
  tableData['all'] = all
  return [{
    type: 'form',
    props: {
      form: getFormSetting(tableData)
    }
  }, {
    type: 'table',
    props: {
      header: getHeader(),
      data: tableData,
      zeroFormat: '0',
      export: 'sample_detail'
    }
  }]
}

export default fn

